<template>
  <div class="register">


    <el-dialog :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <div slot="title" class="titleTab">
        <div :class="activeName == 1 ? 'active' : 'inActive'" @click="tabChange(1)">
          摄像头抓拍
        </div>
      </div>

      <div class="contentTab">
        <div class="photo" v-if="activeName == 1">
          <div class="photo-top">
            <div class="left">
              <video style="width: 100%" id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight"
                autoPlay></video>
              <div style="text-align: center; padding-top: 20px">
                <el-button type="primary" @click="photographBtn" size="small">拍摄</el-button>
              </div>
            </div>
            <div class="right">
              <div class="exampleTwo">
                <canvas id="canvasCamera" class="canvas" :width="125" :height="160"></canvas>
                <canvas style="display: none" id="canvasCamera1" class="canvas" :width="330" :height="420"></canvas>
              </div>
            </div>
          </div>
          <div class="desc">
            <span>注意事项：</span>
            <span>1.图像大小建议尺寸为220*280像素:</span>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="submitHandle">确 定</el-button>
          </span>
        </div>
      </div>
    </el-dialog>



    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
      <h3 class="title">新生注册</h3>
      <div style="height: 60vh;overflow-y: scroll; width: 55vw;overflow-x:hidden;">

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item prop="userId">
              <el-input v-model="registerForm.userId" type="text" auto-complete="off" placeholder="账号">
                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="userName">
              <el-input v-model="registerForm.userName" type="text" auto-complete="off" placeholder="姓名">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" auto-complete="off" placeholder="密码"
                @keyup.enter.native="handleRegister">
                <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" auto-complete="off" placeholder="确认密码"
                @keyup.enter.native="handleRegister">
                <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item prop="familyContactName">
              <el-input v-model="registerForm.familyContactName" type="text" auto-complete="off" placeholder="家庭联系人姓名">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="familyContactPhone">
              <el-input v-model="registerForm.familyContactPhone" type="text" auto-complete="off" placeholder="家庭联系人电话">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item prop="sex" label="性别">
              <el-select v-model="registerForm.sex" placeholder="请选择性别">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
                <el-option label="男" :value="0"></el-option>
                <el-option label="女" :value="1"></el-option>
                <el-option label="未知" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="graduateSchool">
              <el-input v-model="registerForm.graduateSchool" type="text" auto-complete="off" placeholder="毕业学校">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item prop="domicileAddress">
              <el-input type="textarea" v-model="registerForm.domicileAddress" auto-complete="off" placeholder="现居地址">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="homeAdress">
              <el-input v-model="registerForm.homeAdress" type="textarea" auto-complete="off"
                placeholder="家庭住址(与身份证上地址一致)">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item prop="telphone">
              <el-input v-model="registerForm.telphone" type="text" auto-complete="off" placeholder="本人手机号">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="identyNo">
              <el-input v-model="registerForm.identyNo" type="text" auto-complete="off" placeholder="本人身份证号">
                <svg-icon slot="prefix" icon-class="edit" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item prop="faceImage" label="本人头像">
          <div @click="photoUploadHandle" style="cursor: pointer;">
            <i class="el-icon-camera-solid" style="color: #d7dbec; font-size: 22px"></i>点击摄像头拍照
          </div>
          <image-upload v-model="registerForm.faceImage" :limit="1" ref="upload" v-show="false" />

          <!-- <el-button @click="vali">验证</el-button> -->
        </el-form-item>



      </div>

      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input v-model="registerForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
          @keyup.enter.native="handleRegister">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="register-code">
          <img :src="codeUrl" @click="getCode" class="register-code-img" />
        </div>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
          @click.native.prevent="handleRegister">
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right;">
          <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>Copyright © 2018-2023 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, stuReg, validateImg } from "@/api/login";
import { getToken } from "@/utils/auth";

export default {
  name: "Register",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      os: true, //控制摄像头开关
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      imgSrc: "",
      activeName: "1", //弹窗的标题栏高亮
      videoWidth: 544,
      videoHeight: 418,
      dialogVisible: false,//弹窗的显隐
      imgSubSrc: "",


      imgSrc: "",
      codeUrl: "",
      registerForm: {
        userId: "",
        password: "",
        confirmPassword: "",
        code: "",
        uuid: "",
        sex: 0,

      },
      registerRules: {
        userId: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
        userName: [
          { required: true, trigger: "blur", message: "请输入您的姓名" },
          { min: 1, max: 50, message: '用户姓名长度必须介于 1 和 50 之间', trigger: 'blur' }
        ],
        sex: [
          { required: true, trigger: "blur", message: "请选择您的性别" }
        ],
        familyContactName: [
          { required: true, trigger: "blur", message: "请输入您的家庭联系人姓名" },
          { min: 1, max: 50, message: '家庭联系人姓名长度必须介于 1 和 50 之间', trigger: 'blur' }
        ],
        familyContactPhone: [
          { required: true, trigger: "blur", message: "请输入您的家庭联系人电话" },
          { min: 1, max: 20, message: '家庭联系人电话长度必须介于 1 和 20 之间', trigger: 'blur' }
        ],
        graduateSchool: [
          { required: true, trigger: "blur", message: "请输入您的毕业学校" }
        ],
        domicileAddress: [
          { required: true, trigger: "blur", message: "请输入您的现居地址" }
        ],
        homeAdress: [
          { required: true, trigger: "blur", message: "请输入您的家庭住址" }
        ],
        telphone: [
          { required: true, trigger: "blur", message: "请输入您的手机号" }
        ],
        identyNo: [
          { required: true, trigger: "blur", message: "请输入您的身份证号" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      captchaEnabled: true
    };
  },
  created() {
    this.getCode();
  },
  methods: {
    // 点击图片上传弹窗显示
    photoUploadHandle() {
      this.activeName = 1;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.resetBtn();
        this.openCamera();
      });
    },
    // 调用摄像头权限
    openCamera() {
      console.log("调取权限");
      //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
      this.$nextTick(() => {
        const _this = this;
        this.os = false; //切换成关闭摄像头
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisCancas1 = document.getElementById("canvasCamera1");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisContext1 = this.thisCancas1.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
        // 使用getUserMedia，因为它会覆盖现有的属性。
        // 这里，如果缺少getUserMedia属性，就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: 220, // _this.videoWidth,
            height: 280, // _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function (e) {
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            this.$message({
              message: "没有开启摄像头权限或浏览器版本不兼容",
              type: "warning",
            });
          });
      });
    },
    // 拍照按钮
    photographBtn() {
      // 点击，canvas画图
      this.thisContext.drawImage(this.thisVideo, 0, 0, 125, 160);
      // 获取图片base64链接预览
      this.imgSrc = this.thisCancas.toDataURL("image/jpeg");
    },
    // 清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    // 重置画布
    resetBtn() {
      this.clearCanvas("canvasCamera");
    },
    // 关闭摄像头
    stopCamera() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //切换成打开摄像头
      }
    },
    //关闭弹窗
    handleClose() {
      this.dialogVisible = false;

      if (this.activeName == 1) {
        this.activeName = 2;
        this.resetBtn();
        this.stopCamera();
        this.os = false;
        this.dialogVisible = false;
      } else {
        this.stopCamera();
        this.dialogVisible = false;
      }
    },
    //点击 摄像头上传确定
    submitHandle() {
      this.dialogVisible = false;
      let file1 = this.base64ToFile(this.imgSrc, "头像.jpg", "image/jpg");
      console.log(file1);
      const formData = new FormData();
      formData.append("file", file1);

      fetch(process.env.VUE_APP_BASE_API + "/common/upload", {
        method: "POST",
        body: formData,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
      })
        .then((response) => response.json())
        .then((json) => {

          if (json.code == 200) {
            this.$message.success("上传成功,可以关闭页面并点击注册按钮进行注册");
            this.registerForm.faceImage = json.fileName;
          }else{
            this.$message.error(json.msg);
          }
        })
        .catch(error => {
          // 处理上传错误
          console.error("File upload failed:", error);
        });

    },
    base64ToFile(base64, filename, contentType) {
      var arr = base64.split(',')  //去掉base64格式图片的头部
      var bstr = atob(arr[1])   //atob()方法将数据解码
      var leng = bstr.length
      var u8arr = new Uint8Array(leng)
      while (leng--) {
        u8arr[leng] = bstr.charCodeAt(leng) //返回指定位置的字符的 Unicode 编码
      }
      return new File([u8arr], filename, { type: contentType })
    },



    //验证头像
    async vali() {
      const res = await validateImg(this.registerForm);
      return res.msg;
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.registerForm.uuid = res.uuid;
        }
      });
    },
    //注册d
    async handleRegister() {
      let isVali = await this.vali();
      if (isVali !== true ) {
        this.$message.error("头像验证失败,请重新拍照验证");
        return;
      }
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // console.log(this.registerForm);
          // return;
          stuReg(this.registerForm).then(res => {
            const username = this.registerForm.userId;
            this.$alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", '系统提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              this.$router.push("/login");
            }).catch(() => { });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          })
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background-1.png");
  background-size: contain;
  background-repeat: no-repeat;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.register-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.register-code-img {
  height: 38px;
}
</style>
